<template>
	<view class="content">
		<!-- picture -->
		<unicloud-db ref="udb" v-slot:default="{data, loading, error, options}" collection="opendb-mall-goods"
			field="detail_pic,body,_id,sale_price,name,study" :where="swhere" manual getone v-if="showPic">
			<view class="picture">
				<image :src="data.detail_pic" mode="widthFix"></image>			
			</view>
		</unicloud-db>
		<view class="picture">
			<video :src="fileSrc" autoplay controls object-fit="cover" id="myVideo" @timeupdate="videoTimeUpdateEvent" v-if="showVideo"></video>
		</view>
		
		<!-- tab切换 -->
		<u-tabs :list="list" :is-scroll="false" :current="current" @change="change" :active-color="activeColor"
			:font-size="fontSize" :inactive-color="inactiveColor"></u-tabs>
		<!-- tab切换内容 -->

		<view class="tab-content-wrap">
			<!-- 介绍 -->
			<view class="introduce" v-show="current == 0">
				<!-- course-card -->
				<unicloud-db ref="udb" v-slot:default="{data, loading, error, options}" collection="opendb-mall-goods"
					field="detail_pic,body,_id,sale_price,name,study,validity,integral,activity,goods_status"
					:where="swhere" manual getone>
					<view class="course-card-content">
						<view class="course-card">
							<view class="title">
								<text>{{data.name}}</text>
							</view>
							<view class="number">
								<text>{{data.study}}人学过</text>
							</view>
							<view class="term">
								<text>有效期：{{data.validity}}</text>
							</view>
							<view class="bottom">
								<view class="price">
									<text>￥{{data.sale_price}}</text>
								</view>
								<view class="score" v-if="data.integral != 0">
									<view class="left">
										<text>赠送</text>
									</view>
									<view class="right">
										<text>{{data.integral}}积分</text>
									</view>
								</view>
								<!-- <view class="score" v-if="data.activity != ''">
									<view class="left">
										<text>活动</text>
									</view>
									<view class="right">
										<text>{{data.activity}}</text>
									</view>
								</view> -->
								<view class="update" v-if="data.goods_status == 0">
									<text>更新中</text>
								</view>
								<view class="update" v-if="data.goods_status == 1">
									<text>已完成</text>
								</view>
								<view class="update" v-if="data.goods_status == 2">
									<text>已下架</text>
								</view>
							</view>
						</view>
					</view>
				</unicloud-db>
				<!-- teacher -->
				<unicloud-db ref="udb" v-slot:default="{data, loading, error, options}"
					collection="opendb-mall-goods,teacher-info" field="teacher_id{teacher_avatar,teacher_name}"
					:where="twhere" manual getone>
					<view class="teacher-content">
						<view class="teacher">
							<view class="title">
								<text>讲师</text>
							</view>
							<view class="bottom">
								<view class="left">
									<view class="img-box">
										<image :src="data.teacher_id[0].teacher_avatar" mode=""></image>
									</view>
									<view class="name">
										<text>{{data.teacher_id[0].teacher_name}}</text>
									</view>
								</view>
								<view class="right">
									<text>讲师主页</text>
									<u-icon name="arrow-right" color="#B6B6B6" size="28"></u-icon>
								</view>
							</view>
						</view>
					</view>
				</unicloud-db>
				<!-- course-introduce -->
				<unicloud-db ref="udb" v-slot:default="{data, loading, error, options}" collection="opendb-mall-goods"
					field="course_intro" :where="swhere" manual getone>
					<view class="introduce-content" v-if="data.course_intro != ''">
						<view class="course-introduce">
							<view class="title">
								<text>课程简介</text>
							</view>
							<rich-text :nodes="data.course_intro"></rich-text>
						</view>
					</view>
				</unicloud-db>
			</view>
			<!-- 课程 -->
			<view class="course" v-if="current == 1">
				<view class="course-content">
					<u-collapse :accordion="accordion" @change="changeCollapse" :head-style="headStyle" v-if="!showNothing">
						<u-collapse-item :index="index" @change="itemChange" :title="item"
							v-for="(item, index) in chapterList" :key="index" :open="index == 0?true:false">
							<view class="collapse-item" v-for="(item1,index1) in courseList" :key="index1" v-if="item1.chapter_id[0].course_chapter == item" @click="toLook(item1.tag,item1.course_file,item1.status,item1.freed_time)">
								<view class="left">
									<view class="tag">
										<text v-if="item1.tag == 0">图文</text>
										<text v-if="item1.tag == 1">视频</text>
										<text v-if="item1.tag == 2">音频</text>
									</view>
									<view class="title">
										<text>{{index1+1}}.{{item1.second_level_title}}</text>
									</view>
								</view>
								<view class="right" v-if="!course_show_flag">
									<view class="watch" v-if="item1.status==0">
										<text>可试看</text>
									</view>
									<view class="listen" v-if="item1.status==1">
										<text>可试听</text>
									</view>
									<view class="lock" v-if="item1.status==2">
										<u-icon name="lock" color="#34373E" size="28"></u-icon>
									</view>
									<view class="buyed" v-if="item1.status==3">
										<text>查看</text>
									</view>
								</view>
								<view class="right" v-if="course_show_flag">
									<view class="buyed">
										<text>查看</text>
									</view>
								</view>
							</view>
						</u-collapse-item>
					</u-collapse>
					<view class="u-empty-box" v-if="showNothing">
						<u-empty text="暂无数据" mode="data"></u-empty>
					</view>
				</view>
			</view>
			<!-- 附件 -->
			<!-- <view class="enclosure" v-if="current == 2">
				<view class="u-empty-box">
					<u-empty text="暂无数据" mode="data" v-if=""></u-empty>
				</view>
			</view> -->
			<!-- 评价 -->
			<view class="evaluate" v-show="current == 2">
				<view class="u-empty-box" v-if="showNoData">
					<u-empty text="暂无数据" mode="data"></u-empty>
				</view>
			</view>
			<!-- 题库 -->
			<!-- <view class="question" v-if="current == 4">
				<question-bank></question-bank>
			</view> -->
		</view>

		<!-- tabbar -->
		<view class="tabbar-content">
			<view class="empty-box">

			</view>
			<unicloud-db ref="udb" v-slot:default="{data, loading, error, options}" collection="opendb-mall-goods"
				field="detail_pic,body,_id,sale_price,name,study" :where="swhere" manual getone>
				<view class="tabbar">
					<view class="left">
						<view class="left-item" @click="tohome">
							<view class="icon">
								<u-icon name="home" color="#34373E" size="28"></u-icon>
							</view>
							<text>首页</text>
						</view>
						<view class="left-item">
							<view class="icon">
								<u-icon name="star" color="#34373E" size="28"></u-icon>
							</view>
							<text>收藏</text>
						</view>
						<view class="left-item">
							<view class="icon">
								<u-icon name="share" color="#34373E" size="28"></u-icon>
							</view>
							<text>分享</text>
						</view>
					</view>
					<view class="right" @click="purchase(data)">
						<text>立即购买</text>
					</view>
				</view>
			</unicloud-db>
		</view>

	</view>
</template>

<script>
	import questionBank from './components/question-bank.vue'
	export default {
		data() {
			return {
				// tabs切换
				list: [{
					name: '介绍'
				}, {
					name: '课程'
				}, {
					name: '评价'
				}],
				current: 0,
				activeColor: '#04BA8F',
				fontSize: '32',
				inactiveColor: '#666666',
				courseId: '',
				swhere: "",
				twhere: "",
				cwhere: "",
				//折叠面板
				accordion: false,
				headStyle: {
					backgroundColor: '#F7F8FC',
					padding: '20rpx'
				},
				chapterList:[],//章节标题
				courseList: [],
				showNothing: false,//课程的暂无数据
				showNoData: true,//评论的暂无数据
				course_show_flag:false, //判断是否购买了该课程
				unpaid:false,//判断是否有该课程的未支付订单
				showPic: true,
				showVideo:false,
				fileSrc:'',
				videoContext: {},  // 用于绑定视频标签
				freed_time: '',
				outTradeNoStr:''
			}
		},
		components: {
			questionBank
		},
		onLoad(e) {
			this.courseId = e.courseId;
			this.swhere = "_id=='" + e.courseId + "'";
			this.twhere = "teacher_id._id=='" + e.tid + "'";
			// this.cwhere = "course_id._id=='" + e.courseId + "'";
			console.log(this.swhere, this.twhere);
			this.judgeCourseStatus();
			this.searchOrder();
		},
		onReady() {
			if (this.courseId) {
				this.$refs.udb.loadData()
			}
		},
		created() {
			// 创建视频实例指向视频控件
			this.videoContext = uni.createVideoContext('myVideo');
		},
		watch: {
			current(newVal, oldVal) {
				console.log(newVal)
				if (newVal == 1) {
					this.showCourse();
				}
			}
		},
		methods: {
			videoTimeUpdateEvent(e) { // 播放进度改变
				// e.detail.currentTime为每次触发时,视频的当前播放时间
				let currentTime = Number(e.detail.currentTime);
				// console.log('播放进度条改变', currentTime)
				// 试看结束 this.freed_time为试看时间
				if (this.freed_time != '' && currentTime >= this.freed_time) {
					// 试看结束,在这做一些想做的操作,例如停止视频播放
					this.videoContext.exitFullScreen();
					this.videoContext.pause();
					this.videoContext.seek(0);
				}
			},
			toLook(tag,file,status,freed_time){
				console.log(tag,file,status,freed_time)
				this.freed_time = '';
				if(status != 3 && !this.course_show_flag){
					this.freed_time = freed_time;
				}
				if(tag == 0){//图文
					this.showPic = true;
					this.showVideo = false;
					uni.showToast({
						title:'跳转新页面',
						icon:"none"
					})
					return
				}
				if(tag != 0){//视频 或 音频
					this.showPic = false;
					this.showVideo = true;
					this.fileSrc = file;
					return
				}
			},
			searchOrder(){
				var that = this;
				const user_id = uni.getStorageSync('user_id');
				const db = uniCloud.database()
				db.collection('order,userinfo,opendb-mall-goods')
					.where("user_id._id=='" + user_id +"' && course_id._id=='" + that.courseId + "' && pay_status == 0")
					.field('user_id{username},course_id{name},pay_status,outTradeNo')
					.get()
					.then(res => {
						console.log('so', res);
						if(res.result.data.length != 0){
							that.unpaid = true;
							that.outTradeNoStr = res.result.data[0].outTradeNo;
							return
						}
					}).catch(err => {
						console.error(err)
					})
			},
			judgeCourseStatus(){
				const user_id = uni.getStorageSync('user_id');
				const db = uniCloud.database()
				db.collection('order,userinfo,opendb-mall-goods')
					.where("user_id._id=='" + user_id +"' && course_id._id=='" + this.courseId + "' && pay_status == 1")
					.field('user_id{username},course_id{name},pay_status')
					.get()
					.then(res => {
						console.log('cs', res);
						if(res.result.data.length != 0){
							this.course_show_flag = true;
							return
						}
					}).catch(err => {
						console.error(err)
					})
			},
			showCourse() {
				const db = uniCloud.database()
				db.collection('course-detail,course-chapter')
					.where("chapter_id.course_id=='" + this.courseId + "'")
					.field('chapter_id{course_chapter},second_level_title,tag,status,course_file,freed_time')
					.get()
					.then(res => {
						console.log('cc', res, res.result.data);
						this.courseList = res.result.data;
						if(res.result.data.length != 0){
							let arr = [];
							res.result.data.forEach((item,index)=>{
								console.log(arr.indexOf(item.chapter_id[0].course_chapter))
								if(arr.indexOf(item.chapter_id[0].course_chapter) == -1){
									arr.push(item.chapter_id[0].course_chapter)
								} 
							})
							console.log('arr',arr)
							this.chapterList = arr;
						}else{
							this.showNothing = true;
						}
					}).catch(err => {
						console.error(err)
					})
			},
			purchase(courseObj) {
				var that = this;
				if(that.course_show_flag){
					uni.showToast({
						title:"已购买成功",
						icon:"none"
					})
					return
				}
				const body = courseObj.body;
				let outTradeNo = '';
				if(!that.unpaid){
					outTradeNo = ((Math.round(new Date())).toString() + (courseObj._id).toString()).substring(0,
						25) + (parseInt(Math.random() * 100000)).toString();
				}else{
					outTradeNo = that.outTradeNoStr;
				}
				
				const totalFee = courseObj.sale_price * 100;
				console.log(body, outTradeNo, totalFee)
				const openid = uni.getStorageSync("openid");
				uniCloud.callFunction({
					name: 'getOrderInfo',
					data: {
						openid: openid,
						body: body,
						outTradeNo: outTradeNo,
						totalFee: totalFee,
					},
					success(res) {
						var orderInfo = res.result.orderInfo
						if (orderInfo) {
							return new Promise((resolve, reject) => {
								uni.requestPayment({
									provider: 'wxpay',
									timeStamp: orderInfo.timeStamp,
									nonceStr: orderInfo.nonceStr,
									package: orderInfo.package,
									signType: orderInfo.signType,
									paySign: orderInfo.paySign,
									success: function(res) {
										console.log('success:' + JSON.stringify(res));
										if(!that.unpaid){
											const user_id = uni.getStorageSync("user_id");
											const db = uniCloud.database()
											db.collection('order').add({
													outTradeNo:outTradeNo,
													total_price:courseObj.sale_price,
													pay_status:1,
													user_id:user_id,
													course_id:that.courseId
												})
												.then(res => {
													console.log(res);
													uni.showToast({
														title:'支付成功',
														icon:"none"
													})
													that.judgeCourseStatus();
												}).catch(err => {
													console.error(err)
													uni.showToast({
														title:'支付失败',
														icon:"none"
													})
												})
										}else if(that.unpaid){
											const user_id = uni.getStorageSync("user_id");
											const db = uniCloud.database()
											db.collection('order')
												.where("user_id=='" + user_id +"' && course_id=='" + that.courseId + "' && pay_status == 0")
												.update({
													pay_status: 1
												})
												.then(res => {
													console.log('upo', res);
													if (res.result.updated == 1) {
														uni.showToast({
															title:'支付成功',
															icon:"none"
														})
														that.course_show_flag = true;
													}
												}).catch(err => {
													console.error(err)
													uni.showToast({
														title:'支付失败',
														icon:"none"
													})
												})
										}
									},
									fail: function(err) {
										console.log('fail:' + JSON.stringify(err));
										
										if(!that.unpaid){
											const user_id = uni.getStorageSync("user_id");
											const db = uniCloud.database()
											db.collection('order').add({
													outTradeNo:outTradeNo,
													total_price:courseObj.sale_price,
													pay_status:0,
													user_id:user_id,
													course_id:that.courseId
												})
												.then(res => {
													console.log('succ',res);
													that.unpaid = true;
													that.outTradeNoStr = outTradeNo;
												}).catch(err => {
													console.error('err',err)
												})
										}
										uni.showToast({
											title:'支付失败',
											icon:"none"
										})
									}
								});
							})
						}
					},
					fail(res) {
						console.log(res)
					}
				})
			},
			change(index) {
				this.current = index;
			},
			tohome() {
				uni.navigateBack({
					delta: 1
				})
			},
			changeCollapse(index) {
				console.log('i', index)
			},
			itemChange(index) {
				console.log('item', index)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		background-color: #FAFAFA;
		.u-empty-box{
			padding-top: 200rpx;
			background-color: #fff;
		}
		//picture
		.picture {
			width: 750rpx;
			text-align: center;
			// height: 460rpx;

			image {
				width: 100%;
				height: 100%;
			}
			video{
				width: 100%;
				// height: 100%;
			}
			audio{
				width: 100%;
				// height: 100%;
			}
		}

		// tab切换内容
		.tab-content-wrap {
			border-top: 1px solid #f1f1f1;

			// 介绍
			.introduce {}

			//课程
			.course {
				background-color: #fff;
				// padding: 20rpx;

			}

			//附件
			.enclosure {}

			//评价
			.evaluate {}

			//题库
			.question {}
		}
	}

	//course-card
	.course-card-content {
		padding: 40rpx 30rpx;
		background-color: #fff;

		.course-card {
			position: relative;

			.title {
				color: #333333;
				font-size: 32rpx;
			}

			.number {
				color: #666666;
				font-size: 22rpx;
				margin-top: 20rpx;
			}

			.term {
				color: #666666;
				font-size: 24rpx;
				margin-top: 20rpx;
			}

			.bottom {
				display: flex;
				flex-wrap: wrap;
				margin-top: 20rpx;

				.price {
					color: #F56C6C;
					font-size: 32rpx;
					font-weight: bold;
				}

				.score {
					display: flex;
					flex-wrap: wrap;
					margin-left: 20rpx;

					.left {
						width: 60rpx;
						height: 35rpx;
						background-color: #FF505C;
						color: #fff;
						font-size: 24rpx;
						text-align: center;
					}

					.right {
						// width: 86rpx;
						padding: 0 10rpx;
						height: 35rpx;
						background-color: #FFE3B5;
						color: #333333;
						font-size: 24rpx;
						text-align: center;
					}
				}
			}

			.update {
				position: absolute;
				top: 50rpx;
				right: 0;
				width: 80rpx;
				height: 35rpx;
				background-color: #EAEAEA;
				color: #333333;
				font-size: 24rpx;
				text-align: center;
			}
		}
	}

	//teacher
	.teacher-content {
		margin-top: 20rpx;

		.teacher {
			background-color: #fff;
			padding: 30rpx;

			.title {
				font-size: 32rpx;
			}

			.bottom {
				display: flex;
				justify-content: space-between;
				margin-top: 30rpx;

				.left {
					display: flex;
					flex-wrap: wrap;

					.img-box {
						width: 90rpx;
						height: 90rpx;
						border-radius: 45rpx;
						overflow: hidden;

						image {
							width: 100%;
							height: 100%;
						}
					}

					.name {
						font-size: 32rpx;
						margin: 26rpx 0 0 20rpx;
					}
				}

				.right {
					color: #B6B6B6;
					font-size: 26rpx;
					margin-top: 26rpx;
				}
			}
		}
	}

	.introduce-content {
		margin-top: 20rpx;

		.course-introduce {
			background-color: #fff;
			padding: 30rpx;

			.title {
				font-size: 30rpx;
			}
		}
	}

	.course-content {
		
		//折叠面板
		.collapse-item {
			display: flex;
			justify-content: space-between;
			height: 60rpx;
			padding: 20rpx;

			.left {
				display: flex;
				flex-wrap: wrap;

				.tag {
					width: 68rpx;
					height: 28rpx;
					border-radius: 10rpx;
					border: 1px solid #36373B;
					font-size: 24rpx;
					color: #34373E;
					text-align: center;
					padding-bottom: 6rpx;
					margin-right: 20rpx;
				}

				.title {
					color: #34373E;
					font-size: 30rpx;
				}
			}

			.right {
				color: #04BA8F;
				font-size: 24rpx;
			}
		}
	}

	//底部导航
	.tabbar-content {
		background-color: #fff;

		.empty-box {
			height: 120rpx;
		}

		.tabbar {
			position: fixed;
			bottom: 0;
			height: 100rpx;
			width: 710rpx;
			z-index: 99;
			background-color: #fff;
			border-top: 1px solid #ccc;
			padding: 0 20rpx;
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;

			.left {
				display: flex;
				flex-wrap: wrap;

				.left-item {
					display: flex;
					flex-direction: column;
					flex-wrap: wrap;
					font-size: 26rpx;
					width: 100rpx;

					.icon {
						margin: 15rpx 0 5rpx 10rpx;
					}
				}
			}

			.right {
				width: 400rpx;
				height: 55rpx;
				border-radius: 35rpx;
				background-color: #04BA8F;
				color: #fff;
				text-align: center;
				padding-top: 15rpx;
				margin-top: 15rpx;
			}
		}
	}
</style>
